import {Voucher} from 'cascadium-ledger';

import {unifyCols} from '../unify-cols';

const WARNINGS = {
  DUP_IDS : '核算科目序时账中仍然存在重复的ID，可能是仍然存在重复的核算方式，也可能是因为年初不规范的结转凭证，请核实后再进行后续操作。'
}

const procJournal = (data) => {
  const entries = unifyCols(data, {EntryCons: Voucher});
  
  for (let i = entries.length - 1; i >= 0; i--) {
    entries[i].attr.style = 'details';
  }

  return entries
    .filter(({voucherID}) => !voucherID.includes('undefined'))
    .filter(({month}) => month > 0 && month <= 12)
    .grip(({voucherID}) => voucherID.split('-').slice(0, 4).join('-'))
    .grap(([voucherID, entries]) => {
      const voucher = Voucher.from(entries, {voucherID, emptyIdent: true});
      voucher.attr.style = 'voucher';
      return voucher;
    });
}

const checkDupID = (list) => {
  const IDs = list.map(({voucherID}) => voucherID);

  if (IDs.length !== [...new Set(IDs)].length) {
    console.warn(WARNINGS['DUP_IDS']);
  }
}

const procDetailedJournal = (data, books) => {

  const filterItemType = (excludedTypes) => 
    ({attr:{itemTypeName}}) => !excludedTypes.includes(itemTypeName)

  const {data: JOURNAL} = books.find(({name}) => name === 'JOURNAL');
  const journalEntries = JOURNAL.map(({succ}) => succ).flat();


  let detailedJournal = unifyCols(data, {EntryCons:Voucher})
  .filter(filterItemType(['部门', '项目']));

  console.log('凭证行编号无重复', Object.values(JOURNAL.grip('voucherID').getDict()).every(val => val.length === 1));

  journalEntries.mergeFrom(detailedJournal, {
    mergeKey: 'voucherID',
    mergeFunc: ({source, target}) => {
      target.curr = source.curr;
    }
  });

  return JOURNAL;
}

const importProc = (name, data, books) => {

  const [sheet] = Object.values(data);

  if (name === 'JOURNAL') {
    return procJournal(sheet, books);
  }

  if (name === 'DETAILED') {
    return procDetailedJournal(sheet, books);
  }
}

const cols = {
  voucherID:    {desc:'凭证编号', width: 150, isSortable: true, isFilterable: true},
  'curr.code':  {desc:'科目代码', width: 50, isFilterable: true},
  'curr.name':  {desc:'科目名称', width: 50, isFilterable: true},
  'accrual.dr': {desc:'借方发生', width: 30, type:'number', isSortable: true},
  'accrual.cr': {desc:'贷方发生', width: 30, type:'number', isSortable: true},
  desc:         {desc:'凭证信息', width: 350, isFilterable: true}
}

export default {
  name: 'JOURNAL',
  descAddi: 'Journal',
  desc: '序时账',
  cols,
  data: [],
  dataTool: {
    useImport: {
      dataSpecs: [
        {
          name: 'JOURNAL',
          desc: '总序时账'
        },
        {
          name: 'DETAILED',
          desc: '明细科目（辅助核算）序时账'
        },
      ],
      proc: importProc,
    },
  },
}
